package com.sailboard.iot.opm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sailboard.iot.opm.common.JsonResult;
import com.sailboard.iot.opm.dao.entity.DepartmentUser;
import com.sailboard.iot.opm.dao.entity.User;
import com.sailboard.iot.opm.dao.entity.UserRole;
import com.sailboard.iot.opm.dao.mapper.DepartmentUserMapper;
import com.sailboard.iot.opm.dao.mapper.UserMapper;
import com.sailboard.iot.opm.service.DepartmentUserService;
import com.sailboard.iot.opm.utils.BeanMapUtils;
import com.sailboard.iot.opm.utils.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Component
public class DepartmentUserServiceImpl implements DepartmentUserService {

    @Resource
    DepartmentUserMapper departmentUserMapper;
    public PageInfo getDepartmentUserList(int pageNum, int pageSize, DepartmentUser departmentUser) {
        PageHelper.startPage(pageNum, pageSize);
        List<DepartmentUser> list = departmentUserMapper.getDepartmentUserList(BeanMapUtils.toMap(departmentUser));
        return new PageInfo(list);
    }

    @Override
    public boolean batchDelete(String ids){
        List<Long> list = new ArrayList<Long>();
        String[] arr = ids.split(",");
        for(String id : arr) {
            Long ID = Long.valueOf(id);
            list.add(ID);
        }
        return departmentUserMapper.batchDelete(list) > 0;
    }

    public boolean add(DepartmentUser departmentUser){
        return departmentUserMapper.insertSelective(departmentUser) == 1;
    }

    public boolean edit(DepartmentUser departmentUser){
        return departmentUserMapper.updateByPrimaryKeySelective(departmentUser) == 1;
    }

    public JsonResult bindDepartment(Long userId, String departmentIds) {
        try {
            departmentUserMapper.deleteByUserId(userId);
            if(StringUtils.isEmpty(departmentIds)) {
                return JsonResult.success();
            }
        } catch (Exception e) {
            return JsonResult.error();
        }
        String[] ids = departmentIds.split(",");
        List<DepartmentUser> list = new ArrayList<>();
        for(String id : ids) {
            DepartmentUser departmentUser = new DepartmentUser();
            departmentUser.setUserId(userId);
            departmentUser.setDepartmentId(Long.valueOf(id));
            list.add(departmentUser);
        }
        int row = departmentUserMapper.batchInsert(list);
        return row > 0 ? JsonResult.success() : JsonResult.error();
    }
}
